<template>
  <div class="cont-main ">
    <div class="menu-body common-content">
      <div class="top-search-bar">
        <el-form size="small" ref="queryForm" inline>
          <el-form-item label="">
            <el-input @input="search"
                      v-model="searCh.roleChName"
                      clearable
                      placeholder="角色中文名"></el-input>
          </el-form-item>
          <el-form-item label="">
            <el-input @input="search"
                      v-model="searCh.roleEnName"
                      clearable
                      placeholder="角色英文名"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button
                type="primary"
                icon="el-icon-search"
                @click="search()">搜索
            </el-button>
            <el-button
                type="primary"
                icon="el-icon-refresh-right"
                @click="searchGo0()">刷新
            </el-button>
            <el-button
                v-if="auth&&auth.add"
                type="primary"
                icon="el-icon-plus"
                @click="addRole()">新增
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <Table
          ref="table"
          :table-header="tableHeader"
          :tableData="tableData"
          :pg-total-num="total"
          :max-height="tableMaxHeight"
          @handleOnEdit="btndetail"
          @handlepdelete="pdelete"
          @handleSizeChange="handleSizeChange"
          @handleCurrentChange="handleCurrentChange">
        <div slot="operation" slot-scope="row">
          <i class="el-icon-s-check table-btn" @click="getRoleTree(row)" title="角色权限"></i>
          <i class="el-icon-edit table-btn" @click="edi(row)" title="修改角色" v-if="auth&&auth.edit"></i>
          <i class="el-icon-delete table-btn del" @click="del(row)" title="角色删除" v-if="auth&&auth.del"></i>
        </div>
      </Table>
    </div>

    <!--角色新增 / 角色编辑-->
    <Dialog
        :addNewVisible="roleVisible"
        @closeDia="closeDia"
        width="720px"
        :center="true"
        :title="flag == 1 ? '角色新增' : '角色编辑'">
      <div slot="elform">
        <el-form
            :model="form"
            :rules="rules"
            ref="formName"
            size="small"
            label-width="100px">
          <el-row>
            <el-col :span="24">
              <el-form-item label="角色中文名" prop="roleChName">
                <el-input v-model="form.roleChName"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="角色英文名" prop="roleEnName">
                <el-input v-model="form.roleEnName"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="备注">
                <el-input type="textarea" v-model="form.remarks"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button size="small" @click="closeDia">取 消</el-button>
          <el-button size="small" type="primary" @click="addroleBtn">确 定</el-button>
        </div>
      </div>
    </Dialog>

    <!--角色权限-->
    <Dialog
        :addNewVisible="TreeVisible"
        @closeDia="closeDia"
        width="500px"
        :center="true"
        title="角色权限">
      <div slot="elform" class="">
        <div class="role-body-group" style="height: 300px">
          <el-scrollbar style="height: 100%">
            <!-- 滚动条要包裹的内容 -->
            <el-tree
                :data="TreeData"
                show-checkbox
                check-strictly
                node-key="id"
                :props="defaultProps"
                ref="treeList">
            </el-tree>
          </el-scrollbar>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button size="small" @click="closeDia">取 消</el-button>
          <el-button size="small" type="primary" @click="addTreeBtn">确 定</el-button>
        </div>
      </div>
    </Dialog>

  </div>
</template>

<script>
import Table from "@/components/Table";
import Dialog from "@/components/Dialog/Dialog";
import {
  get_RoleListByPage,
  put_roleAdd,
  del_roleDel,
  put_roleedi,
  get_getRoleTree,
  put_roleMenuAdd,
} from "@/apis/user/userApi";
import {debounce} from '@/utils'

export default {
  aside: 'comp/CompAside',
  components: {Table, Dialog},
  data() {
    return {
      auth: null,
      tableMaxHeight: '50px',
      rules: {
        roleChName: [
          {required: true, message: "请输入角色中文名", trigger: "blur"},
        ],
        roleEnName: [
          {required: true, message: "请输入角色英文名", trigger: "blur"},
        ]
      },
      searchData: {
        time: null,
        searchName: "",
        status: "",
        protocol: "",
      },

      dialogVisible: false,
      nowPage: 1,
      total: 0,
      currentPage: 1,
      pageSize: 10,
      detailForm: {},
      tableData: [],
      selectData: [],
      tableHeader: [
        {prop: "roleChName", name: "角色中文名", minWidth: 100},
        {prop: "roleEnName", name: "角色英文名", minWidth: 100},
        {prop: "addTime", name: "添加时间", minWidth: 100},
        {prop: "editTime", name: "修改时间", minWidth: 100},
        {prop: "remarks", name: "备注", minWidth: 100},
        {prop: "operation", name: "操作", minWidth: 100, slot: true}
      ],
      tables: [],
      roleVisible: false,
      flag: 1,
      form: {
        roleChName: "",
        roleEnName: "",
        remarks: "",
      },
      defaultProps: {
        children: "children",
        label: "title",
      },
      TreeData: [],
      TreeVisible: false,
      rowId: "",
      searCh: {
        roleEnName: "",
        roleChName: "",
      },
      TreeId: [],
    };
  },
  created() {
    this.fetchData();
    this.getRoleList();
  },
  mounted() {
    this.$nextTick(() => {
      this.tableMaxHeight = window.innerHeight - this.$refs.table.$el.offsetTop - 50 - 30 - 48 + 'px'
    })
  },
  methods: {
    //递归获取当前已选择的id
    getTreeId(arr) {
      arr.forEach((item) => {
        if (item.checkArr.isChecked == 1) {
          this.TreeId.push(item.id);
        }
        if (item.children.length > 0) {
          this.getTreeId(item.children);
        }
      });
    },
    //角色当前权限
    getRoleTree(row) {
      this.rowId = row.data.id;
      this.TreeVisible = true;
      get_getRoleTree({id: row.data.id}).then((res) => {
        let {data, code} = res.data;
        this.getTreeId(data);
        this.TreeData = data;
        if (this.$refs.treeList) {
          this.$refs.treeList.setCheckedKeys(this.TreeId);
        }
      });
    },
    //搜索
    search: debounce(function () {
      let tiem = {};
      for (const key in this.searCh) {
        if (this.searCh[key] != "") {
          tiem[key] = this.searCh[key];
        }
      }
      this.getRoleList(tiem);
    }, 100),
    searchGo0() {
      this.getRoleList();
      this.searCh = {
        roleEnName: "",
        roleChName: "",
      };
    },
    //添加/修改角色权限
    addTreeBtn() {
      let arr = [].concat(
        this.$refs.treeList.getCheckedKeys(),
        this.$refs.treeList.getHalfCheckedKeys()
      );
      put_roleMenuAdd({roleId: this.rowId, menuId: arr.join(",")}).then((res) => {
          let {msg, code} = res.data;
          this.$confirm("您更改了权限配置，是否退出重新登录?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }).then(() => {
            this.$store.dispatch('app/loginOut').then(res => {
              this.$router.push({name: 'login'});
            })
          }).catch(() => {
            this.$message.success(msg);
            this.closeDia();
          });
        }
      );
    },
    //编辑角色
    edi(row) {
      this.flag = 2;
      this.roleVisible = true;
      this.form = {
        roleChName: row.data.roleChName,
        roleEnName: row.data.roleEnName,
        remarks: row.data.remarks,
        id: row.data.id,
      };
    },
    //删除角色
    del(row) {
      this.$confirm("此操作将永久删除该角色, 是否继续?", "提示", {
        confirmButtonText: "删除",
        cancelButtonText: "取消",
        type: "error",
        confirmButtonClass: 'el-button--danger'
      }).then(() => {
        del_roleDel({id: row.data.id}).then((res) => {
          let {code, msg} = res.data;
          this.$message.success(msg);
          this.getRoleList();
        });
      }).catch(() => {
      });
    },
    //添加角色
    addRole() {
      this.flag = 1;
      this.roleVisible = true;
    },
    //角色弹框确认
    addroleBtn() {
      if (this.flag == 1) {
        put_roleAdd(this.form).then((res) => {
          let {code, msg} = res.data;
          this.$message.success(msg);
          this.getRoleList();
          this.closeDia();
        });
      } else {
        put_roleedi(this.form).then((res) => {
          let {code, msg} = res.data;
          this.$message.success(msg);
          this.getRoleList();
          this.closeDia();
        });
      }
    },
    //获取角色列表
    getRoleList(val) {
      get_RoleListByPage(
        Object.assign({}, val, {
          pageSize: this.pageSize,
          pageNum: this.nowPage,
          menuId: this.$route.meta.id
        })
      ).then((res) => {
        let {records, total} = res.data.data;
        this.auth = res.data.auth
        if (records.length === 0 && this.nowPage > 1) {
          this.nowPage--;
          this.getRoleList();
        }
        records.forEach((element) => {
          element.isHover = false;
          if (element.addTime) {
            element.addTime = this.$moment(element.addTime).format(
              "YYYY-MM-DD HH:mm:ss"
            );
          }
          if (element.editTime) {
            element.editTime = this.$moment(element.editTime).format(
              "YYYY-MM-DD HH:mm:ss"
            );
          }
        });
        this.tableData = records;
        this.total = total;
      });
    },
    //关闭弹框
    closeDia() {
      this.roleVisible = false;
      this.TreeVisible = false;
      this.clearForm();
    },
    clearForm() {
      if (this.$refs["formName"]) {
        this.$refs["formName"].resetFields();
      }
      this.form = {
        roleChName: "",
        roleEnName: "",
        remarks: "",
      };
      this.TreeId = [];
      if (this.$refs.treeList) {
        this.$refs.treeList.setCheckedKeys(this.TreeId);
      }
    },
    fetchData() {
      this.tableData = [];
      let start = (this.nowPage - 1) * this.pageSize;
      let end =
        this.nowPage * this.pageSize > this.tables.length
          ? this.tables.length
          : this.nowPage * this.pageSize;
      for (let i = start; i < end; i++) {
        this.tableData.push(this.tables[i]);
      }
      this.total = this.tables.length;
      this.currentPage = this.nowPage;
    },
    btndetail(row) {
      this.dialogVisible = true;
      this.detailForm = JSON.parse(JSON.stringify(row));
    },

    handleSizeChange(val) {
      this.pageSize = val;
      this.getRoleList();
    },

    handleCurrentChange(val) {
      this.nowPage = val;
      this.getRoleList();
    },

    clearData() {
      this.tables = [];
      this.getRoleList();
    },

    handleClose() {
      this.dialogVisible = false;
    },
    pdelete(val) {
      this.selectData = val;
    },
  },
};
</script>
<style lang="less" scoped>
  .cont-main {
    height: 100%;
    padding: 15px;

    .menu-body {
      height: 100%;
      padding: 15px;
    }
  }

  .role-body-group {
    max-height: 400px;

    /deep/ .el-tree {
      background-color: transparent;
      color: #ffffff;

      .el-tree-node__content:hover {
        color: #ffffff;
        background-color: rgba(255, 255, 255, 0.2) !important;
      }
    }
  }

</style>
